﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.Practices.Prism.Events;
using QLab.Events;
using System.ComponentModel.Composition;

namespace QLab.Services
{
	[Export(typeof(IStatusBarService))]
	[PartCreationPolicy(CreationPolicy.Shared)]
	public class StatusBarService : IStatusBarService
	{
		private static int DEFAULT_TIMEOUT = 4000;
		private static string DEFAULT_STATUS = "Ready";

		private IEventAggregator _eventAggregator;

		private string _status = DEFAULT_STATUS;
		private int _timeout = DEFAULT_TIMEOUT;
		private Timer _timer;

		[ImportingConstructor]
		public StatusBarService(IEventAggregator EventAggregator)
		{
			_eventAggregator = EventAggregator;
			_timer = new Timer(OnTimerTick);
			Status = DEFAULT_STATUS;
		}

		#region Properties

		public string Status
		{
			get { return _status; }
			set
			{
				_status = value;
				_eventAggregator.GetEvent<StatusChangedEvent>().Publish(_status);
			}
		}

		#endregion

		#region Methods

		public void SetStatus(string Status)
		{
			SetStatus(Status, DEFAULT_TIMEOUT);
		}

		public void SetStatus(string Status, int Timeout)
		{
			this.Status = Status;
			_timer.Change(_timeout, System.Threading.Timeout.Infinite); //Only one timeout
		}

		/// <summary>
		/// Disables timer
		/// </summary>
		/// <param name="UserState">null</param>
		private void OnTimerTick(object UserState)
		{
			Status = DEFAULT_STATUS;
			_timer.Change(Timeout.Infinite, Timeout.Infinite);
		}

		#endregion
	}
}
